package com.xc.pay.weixin.template;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xc.pay.weixin.enums.WxPayUrlEnum;
import com.xc.pay.weixin.modal.v3.base.WxBaseModal;
import com.xc.pay.weixin.template.Base.WxPayDefaultTemplate;
import com.xc.pay.weixin.util.HttpUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * APP模板类
 *
 * @author rongrong
 * @date 2020/11/27
 */
@Slf4j
@SuppressWarnings("unchecked")
@RequiredArgsConstructor
public class WxPayAppTemplate extends WxPayDefaultTemplate {

  /**
   * V3版本统一下单接口
   *
   * @param baseModal 参数Modal
   * @return Object 待定
   */
  @Override
  public JSONObject orderPay(WxBaseModal baseModal) {
    final JSONObject object = super.orderPay(baseModal);
    try {
      final String response =
          HttpUtils.postV3(WxPayUrlEnum.V3_APP_APY.url, object.toJSONString(2), httpClient);
      if (StrUtil.isNotBlank(response)) {
        final JSONObject responseJson = JSONUtil.parseObj(response);
        // 预支付Id
        final String prepayId = responseJson.getStr("prepay_id");
        log.info("预支付ID:{}", prepayId);
        final JSONObject returnObj = getSignReturn();
        returnObj.putOpt("prepayid", prepayId);
        log.info("响应数据：{}", returnObj.toJSONString(2));
        return returnObj;
      }
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("======>下单失败...", e);
    }
  }
}
